import { connect } from 'umi';
import { Select, Button, Message } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
import { PowerStrategyType } from '@/pages/Tianji/DayRollingTradeStrategy/constant.js';

import styles from './index.less';

import {
  computedBenefits,
  computedPrice,
  computedPower,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';
import { useEffect } from 'react';

const { Option } = Select;

const TableOperate = ({
  menuCode,
  originStations,
  stations,
  stationId,
  tradeSeqId,
  hourOrderList,
  selectedRowKeys,
  strategyPowerType,
  marketId,
  dispatch,
}) => {
  /**
   * 切换省份时，修改交易单元列表
   */
  useEffect(() => {
    let stations = originStations.filter((item) => {
      return item.marketId === marketId;
    });
    dispatch({
      type: 'dayRollingTradeStragety/setStations',
      payload: stations,
    });
  }, [marketId]);

  /**
   * 交易单元列表发生变化时，初始化选中交易单元id
   */
  /*   useEffect(() => {
    dispatch({
      type: 'dayRollingTradeStragety/setStationId',
      payload: stations[0]?.value,
    });
  }, [JSON.stringify(stations)]); */

  /**
   * 计算时点收益变动
   */
  const computedBenefitsAsync = async () => {
    if (!selectedRowKeys?.length) {
      return Message.warning('请勾选时点后操作');
    }
    let hourOrderListSimple = hourOrderList
      .filter((item) => {
        return (
          selectedRowKeys.indexOf(item.hourOrder) !== -1 &&
          item.strategyPower !== null &&
          item.strategyPrice !== null
        );
      })
      .map((item) => {
        return {
          hourOrder: item.hourOrder,
          price: item.strategyPrice,
          power:
            strategyPowerType === PowerStrategyType.TARGET_POSITION
              ? parseFloat((item.strategyPower - item.holdings).toFixed(3))
              : item.strategyPower,
        };
      });
    if (!hourOrderListSimple.length) {
      return Message.warning('选择的时点数据不全，无法计算');
    }
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await computedBenefits({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrderList: hourOrderListSimple,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      Message.success('计算收益变动成功');
      let hourResultMapping = res?.data?.hourResultMapping || {};
      // 更新时点数据
      let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
      hourOrderListNew.forEach((item) => {
        if (hourResultMapping[item.hourOrder] !== undefined) {
          item.strategyBenefitsChange =
            hourResultMapping[item.hourOrder] === null
              ? null
              : parseFloat(hourResultMapping[item.hourOrder].toFixed(2));
          item.strategyPowerComputed = false;
          item.strategyPriceComputed = false;
          item.strategyBenefitsComputed = true;
        }
      });
      dispatch({
        type: 'dayRollingTradeStragety/setHourOrderList',
        payload: hourOrderListNew,
      });
    } else {
      Message.error(res.message || '计算收益变动失败');
    }
  };

  /**
   * 计算时点交易价格
   */
  const computedPriceAsync = async () => {
    if (!selectedRowKeys?.length) {
      return Message.warning('请勾选时点后操作');
    }
    let hourOrderListSimple = hourOrderList
      .filter((item) => {
        return selectedRowKeys.indexOf(item.hourOrder) !== -1 && item.strategyPower !== null;
      })
      .map((item) => {
        return {
          hourOrder: item.hourOrder,
          benefits: item.strategyBenefitsChange,
          power:
            strategyPowerType === PowerStrategyType.TARGET_POSITION
              ? parseFloat((item.strategyPower - item.holdings).toFixed(3))
              : item.strategyPower,
        };
      });
    if (!hourOrderListSimple.length) {
      return Message.warning('选择的时点数据不全，无法计算');
    }
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await computedPrice({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrderList: hourOrderListSimple,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      Message.success('计算交易价格成功');
      let hourResultMapping = res?.data?.hourResultMapping || {};
      // 更新时点数据
      let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
      hourOrderListNew.forEach((item) => {
        if (hourResultMapping[item.hourOrder] !== undefined) {
          item.strategyPrice =
            hourResultMapping[item.hourOrder] === null
              ? null
              : parseFloat(hourResultMapping[item.hourOrder].toFixed(2));
          item.strategyPowerComputed = false;
          item.strategyPriceComputed = true;
          item.strategyBenefitsComputed = false;
        }
      });
      dispatch({
        type: 'dayRollingTradeStragety/setHourOrderList',
        payload: hourOrderListNew,
      });
    } else {
      Message.error(res.message || '计算交易价格失败');
    }
  };

  /**
   * 计算策略时点交易量
   */
  const computedPowerAsync = async () => {
    if (!selectedRowKeys?.length) {
      return Message.warning('请勾选时点后操作');
    }
    let hourOrderListSimple = hourOrderList
      .filter((item) => {
        return selectedRowKeys.indexOf(item.hourOrder) !== -1 && item.strategyPrice !== null;
      })
      .map((item) => {
        return {
          hourOrder: item.hourOrder,
          benefits: item.strategyBenefitsChange,
          price: item.strategyPrice,
        };
      });
    if (!hourOrderListSimple.length) {
      return Message.warning('选择的时点数据不全，无法计算');
    }
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await computedPower({
      sequenceId: tradeSeqId,
      unitId: stationId,
      menuCode: menuCode,
      hourOrderList: hourOrderListSimple,
    });
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      Message.success('计算交易量成功');
      let hourResultMapping = res?.data?.hourResultMapping || {};
      // 更新时点数据
      let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
      hourOrderListNew.forEach((item) => {
        if (hourResultMapping[item.hourOrder] !== undefined) {
          item.strategyPower =
            hourResultMapping[item.hourOrder] === null
              ? null
              : strategyPowerType === PowerStrategyType.TARGET_POSITION
              ? parseFloat((hourResultMapping[item.hourOrder] + item.holdings).toFixed(3))
              : parseFloat(hourResultMapping[item.hourOrder].toFixed(3));
          item.strategyPowerComputed = true;
          item.strategyPriceComputed = false;
          item.strategyBenefitsComputed = false;
        }
      });
      dispatch({
        type: 'dayRollingTradeStragety/setHourOrderList',
        payload: hourOrderListNew,
      });
    } else {
      Message.error(res.message || '计算交易量失败');
    }
  };

  return (
    <div className={styles.tableOperate}>
      <Select
        className={styles.stationSelect}
        showSearch
        optionFilterProp="children"
        value={stationId}
        onChange={(value) => {
          dispatch({
            type: 'dayRollingTradeStragety/setStationId',
            payload: value,
          });
        }}
      >
        {stations.map((item) => {
          return (
            <Option value={item.value} key={item.value}>
              {item.label}
            </Option>
          );
        })}
      </Select>
      {/* <div className={styles.batchComputer}>
        <span className={styles.label}>批量策略计算</span>
        <Button className={styles.btn} onClick={computedBenefitsAsync}>
          量+价-&gt;收益
        </Button>
        <Button className={styles.btn} onClick={computedPriceAsync}>
          量+收益-&gt;价
        </Button>
        <Button className={styles.btn} onClick={computedPowerAsync}>
          价+收益-&gt;量
        </Button>
      </div> */}
    </div>
  );
};

export default connect(({ dayRollingTradeStragety, global }) => ({
  menuCode: global.configure.menuCode,
  originStations: dayRollingTradeStragety.originStations,
  stations: dayRollingTradeStragety.stations,
  stationId: dayRollingTradeStragety.stationId,
  tradeSeqId: dayRollingTradeStragety.tradeSeqId,
  hourOrderList: dayRollingTradeStragety.hourOrderList,
  selectedRowKeys: dayRollingTradeStragety.selectedRowKeys,
  strategyPowerType: dayRollingTradeStragety.strategyPowerType,
  marketId: dayRollingTradeStragety.marketId,
}))(TableOperate);
